{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Hikyuu 交互式工具示例\n",
    "=============="
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1、引入交互式工具\n",
    "-----------------\n",
    "需从hikyuu.interactive引入，而不是直接从hikyuu库中引入（hikyuu是一个库，可用于编制其他的工具，而hikyuu.interactive是基于hikyuu库实现的交互式探索工具）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2025-08-11 23:22:04,241 [INFO] runing in interactive session [<module>] (D:\\workspace\\hikyuu\\hikyuu\\__init__.py:109) [hikyuu::hku_info]\n",
      "2025-08-11 23:22:04,241 [INFO] running in jupyter [<module>] (D:\\workspace\\hikyuu\\hikyuu\\__init__.py:116) [hikyuu::hku_info]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "current plugin path: D:\\workspace\\hikyuu\\hikyuu\\plugin\n",
      "2025-08-11 23:22:04.300 [HKU-I] - Using MYSQL BaseInfoDriver (BaseInfoDriver.cpp:57)\n",
      "2025-08-11 23:22:04.326 [HKU-I] - 加载市场信息…… (StockManager.cpp:572)\n",
      "2025-08-11 23:22:04.331 [HKU-I] - 加载证券类型信息…… (StockManager.cpp:590)\n",
      "2025-08-11 23:22:04.336 [HKU-I] - 加载证券信息…… (StockManager.cpp:476)\n",
      "2025-08-11 23:22:04.471 [HKU-I] - 加载权息数据…… (StockManager.cpp:608)\n",
      "2025-08-11 23:22:05.420 [HKU-I] - 加载板块信息…… (StockManager.cpp:181)\n",
      "2025-08-11 23:22:06.582 [HKU-I] - 加载K线数据…… (StockManager.cpp:185)\n",
      "2025-08-11 23:22:06.582 [HKU-I] - 预加载 day K线数据至缓存 (最大数量: 100000)! (StockManager.cpp:229)\n",
      "2025-08-11 23:22:06.583 [HKU-I] - 2.27 秒数据加载完毕. (StockManager.cpp:191)\n",
      "2025-08-11 23:22:06.583 [HKU-I] - 启动行情接收. (SpotAgent.cpp:39)\n",
      "CPU times: total: 1.62 s\n",
      "Wall time: 3.75 s\n"
     ]
    }
   ],
   "source": [
    "#%matplotlib inline\n",
    "%time from hikyuu.interactive import *\n",
    "#use_draw_engine('echarts') #use_draw_engine('matplotlib')  #默认为'matplotlib'绘图"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2、创建交易系统并运行\n",
    "--------------------"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#创建模拟交易账户进行回测，初始资金30万\n",
    "my_tm = crtTM(init_cash = 300000)\n",
    "\n",
    "#创建信号指示器（以5日EMA为快线，5日EMA自身的10日EMA作为慢线，快线向上穿越慢线时买入，反之卖出）\n",
    "my_sg = SG_Flex(EMA(C, n=5), slow_n=10)\n",
    "\n",
    "#固定每次买入1000股\n",
    "my_mm = MM_FixedCount(1000)\n",
    "\n",
    "#创建交易系统并运行\n",
    "sys = SYS_Simple(tm = my_tm, sg = my_sg, mm = my_mm)\n",
    "sys.run(sm['sz000001'], Query(-150))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3、绘制曲线观察\n",
    "---------------"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#绘制系统信号\n",
    "sys.plot()\n",
    "\n",
    "k = sm['sz000001'].get_kdata(Query(-150))\n",
    "c = CLOSE(k)\n",
    "fast = EMA(c, 5)\n",
    "slow = EMA(fast, 10)\n",
    "\n",
    "#绘制信号指示器使用两个指标\n",
    "fast.plot(new=False)\n",
    "slow.plot(new=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "4、绘制资金收益曲线\n",
    "---------------------"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "#绘制资金收益曲线\n",
    "x = my_tm.get_profit_curve(k.get_datetime_list(), Query.DAY)\n",
    "x = PRICELIST(x)\n",
    "x.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "5、回测统计报告\n",
    "----------------------"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "帐户初始金额: 300000.00\n",
      "累计投入本金: 300000.00\n",
      "累计投入资产: 0.00\n",
      "累计借入现金: 0.00\n",
      "累计借入资产: 0.00\n",
      "累计红利: 362.00\n",
      "现金余额: 301532.00\n",
      "未平仓头寸净值: 0.00\n",
      "当前总资产: 301532.00\n",
      "已平仓交易总成本: 0.00\n",
      "已平仓净利润总额: 1532.00\n",
      "单笔交易最大占用现金比例%: 4.14\n",
      "交易平均占用现金比例%: 3.84\n",
      "已平仓帐户收益率%: 0.51\n",
      "帐户年复合收益率%: 1.03\n",
      "帐户平均年收益率%: 1.02\n",
      "赢利交易赢利总额: 1882.00\n",
      "亏损交易亏损总额: -350.00\n",
      "已平仓交易总数: 6.00\n",
      "赢利交易数: 2.00\n",
      "亏损交易数: 4.00\n",
      "赢利交易比例%: 33.33\n",
      "赢利期望值: 255.33\n",
      "赢利交易平均赢利: 941.00\n",
      "亏损交易平均亏损: -87.50\n",
      "平均赢利/平均亏损比例: 10.75\n",
      "净赢利/亏损比例: 5.38\n",
      "最大单笔赢利: 1752.00\n",
      "最大单笔盈利百分比%: 15.83\n",
      "最大单笔亏损: -210.00\n",
      "最大单笔亏损百分比%: -1.80\n",
      "赢利交易平均持仓时间: 45.50\n",
      "赢利交易最大持仓时间: 75.00\n",
      "亏损交易平均持仓时间: 5.50\n",
      "亏损交易最大持仓时间: 13.00\n",
      "空仓总时间: 69.00\n",
      "空仓时间/总时间%: 37.00\n",
      "平均空仓时间: 11.00\n",
      "最长空仓时间: 32.00\n",
      "最大连续赢利笔数: 1.00\n",
      "最大连续亏损笔数: 1.00\n",
      "最大连续赢利金额: 1752.00\n",
      "最大连续亏损金额: -270.00\n",
      "R乘数期望值: 0.02\n",
      "交易机会频率/年: 12.03\n",
      "年度期望R乘数: 0.24\n",
      "赢利交易平均R乘数: 0.09\n",
      "亏损交易平均R乘数: -0.01\n",
      "最大单笔赢利R乘数: 0.16\n",
      "最大单笔亏损R乘数: -0.02\n",
      "最大连续赢利R乘数: 0.16\n",
      "最大连续亏损R乘数: -0.03\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#回测统计\n",
    "from datetime import datetime\n",
    "\n",
    "per = my_tm.get_performance()\n",
    "print(per.report())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "6、关于性能\n",
    "---------------\n",
    "\n",
    "经常有人问到性能问题，下面这段的代码使用之前的系统示例，遍历指定板块的所有股票，计算他们的“盈利交易比例%”（即胜率）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def test_func(stock, query):\n",
    "    \"\"\"计算指定stock的系统策略胜率，系统策略为之前的简单双均线交叉系统（每次固定买入100股）\n",
    "    \"\"\"\n",
    "    #创建模拟交易账户进行回测，初始资金30万\n",
    "    my_tm = crtTM(init_cash = 1000000)\n",
    "\n",
    "    #创建信号指示器（以5日EMA为快线，5日EMA自身的10日EMA作为慢线，快线向上穿越慢线时买入，反之卖出）\n",
    "    my_sg = SG_Flex(EMA(C, n=5), slow_n=10)\n",
    "\n",
    "    #固定每次买入1000股\n",
    "    my_mm = MM_FixedCount(100)\n",
    "\n",
    "    #创建交易系统并运行\n",
    "    sys = SYS_Simple(tm = my_tm, sg = my_sg, mm = my_mm)\n",
    "    sys.run(stock, query)\n",
    "    \n",
    "    per = Performance()\n",
    "    per.statistics(my_tm, Datetime(datetime.today()))\n",
    "    return per[\"赢利交易比例%\".encode('gb2312')]\n",
    "\n",
    "def total_func(blk, query):\n",
    "    \"\"\"遍历指定板块的所有的股票，计算系统胜率\"\"\"\n",
    "    result = {}\n",
    "    for s in blk:\n",
    "        if s.valid and s.type != constant.STOCKTYPE_INDEX:\n",
    "            result[s.name] = test_func(s, query)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "遍历所有当前有效且并非指数的证券。下面是我的机器执行结果，共计算4151支证券，最近500个交易日，共耗时2.89秒。机器配置：Intel i7-4700HQ 2.G。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: total: 5.75 s\n",
      "Wall time: 13.2 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "6902"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time a = total_func(sm, Query(-500))\n",
    "len(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
